<template>
  <div class="upload-excel">
     <div class="left">
      <input
        ref="excel-upload-input"
        class="excel-upload-input"
        type="file"
        accept=".xlsx, .xls"
        @change="handleClick"
      />
      <el-button
        :loading="loading"
        style="margin-left:16px;"
        size="mini"
        type="primary"
        @click="handleUpload"
      >
        点击上传
      </el-button>
    </div>
    <div
      class="right"
      @drop="handleDrop"
      @dragover="handleDragover"
      @dragenter="handleDragover"
    >
      将文件拖到此处
    </div>
  </div>
</template>

<script>
import XLSX from "xlsx";
export default {
  // beforeUpload:
  //onSuccess:读取文件成功之后可以通过这个方法来获取读取成功后的内容
  props: {
    beforeUpload: Function, // 接收一个参数: beforeUpload
    onSuccess: Function, // 接收一个参数:onSuccess
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null,
      },
    };
  },
  methods: {
    //处理获取的数据
    generateData({ header, results }) {
      //分别保存了表头,以及内容到页面上
      this.excelData.header = header;
      this.excelData.results = results;
      //判断是否存在onSuccess,如果存在就执行onSuccess
      this.onSuccess && this.onSuccess(this.excelData);
    },
    handleDrop(e) {
      //阻止事件冒泡
      e.stopPropagation();
      //阻止默认行为
      e.preventDefault();
      if (this.loading) return;
      //得到拖拽过来的文件
      const files = e.dataTransfer.files;
      // 判断文件是否存在
      if (files.length !== 1) {
        this.$message.error("Only support uploading one file!");
        return;
      }
      //得到拖拽的文件
      const rawFile = files[0]; // only use files[0]
      // 判断文件的后缀是否为excel
      if (!this.isExcel(rawFile)) {
        this.$message.error(
          "Only supports upload .xlsx, .xls, .csv suffix files"
        );
        return false;
      }
      //直接将文件中的内容读取出来:先选择beforeUpload 后执行onSuccess
      this.upload(rawFile);
      e.stopPropagation();
      e.preventDefault();
    },
    handleDragover(e) {
      e.stopPropagation();
      e.preventDefault();
      e.dataTransfer.dropEffect = "copy";
    },
    // 点击上传按钮会触发的事件
    handleUpload() {
      // 找到上传框元素,触发它的点击事件:相当于点击了上传框
      this.$refs["excel-upload-input"].click();
    },
    // 当上传框中的按钮发生改变时会触发的方法
    handleClick(e) {
      // 得到选中的目标文件
      const files = e.target.files;
      const rawFile = files[0]; // only use files[0]
      //如果不存在,直接结束代码
      if (!rawFile) return;
      //如果文件存在:触发upload 方法
      this.upload(rawFile);
    },
    // 文件选中之后会粗发的方法
    upload(rawFile) {
      // 将上传框中选中的文件清空
      this.$refs["excel-upload-input"].value = null; // fix can't select the same excel
      // 判断是否存在方法:beforeUpload
      if (!this.beforeUpload) {
        //方法不存在:直接调用方法readerData用来读取excel中的内容
        this.readerData(rawFile);
        return;
      }
      // beforeUpload方法存在:执行方法,方法还有一个返回值:bool值
      // beforeUpload如果返回 false后续读取文件内容方法内容的方法不会执行
      // beforeUpload如果返回true 后续读取文件内容的方法会执行
      const before = this.beforeUpload(rawFile);
      if (before) {
        this.readerData(rawFile);
      }
    },
    //读取选中文件的内容
    readerData(rawFile) {
      //开启加载效果
      this.loading = true;
      //创建一个promise对象
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = (e) => {
          const data = e.target.result;
          //使用execl第三方包来转换数据
          const workbook = XLSX.read(data, { type: "array" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          //得到heard:表头中的内容
          // results:表格中的内容
          const header = this.getHeaderRow(worksheet);
          const results = XLSX.utils.sheet_to_json(worksheet);
          //调用另外一个方法
          this.generateData({ header, results });
          this.loading = false;
          resolve();
        };
        //将文件转为js数据,一旦当他转换完毕会触发它的onload方法
        reader.readAsArrayBuffer(rawFile);
      });
    },
    getHeaderRow(sheet) {
      const headers = [];
      const range = XLSX.utils.decode_range(sheet["!ref"]);
      let C;
      const R = range.s.r;
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
        /* find the cell in the first row */
        let hdr = "UNKNOWN " + C; // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
        headers.push(hdr);
      }
      return headers;
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name);
    },
  },
};
</script>

<style scoped lang="scss">
.upload-excel {
 display: flex;
 width:1000px;
 height: 250px;
 margin: 100px auto;
 border: 3px dashed #ccc;
  .left {
    border-right:3px dashed #ccc;
  }
  .left,
  .right {
   flex: 1;
   display: flex;
   justify-content: center;
   align-items: center;

  }
}
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.drop {
   border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
}
</style>